# -*- coding: utf-8 -*-
import logging
logger = logging.getLogger("appweb")

def cors(self):
    def wrapper():
        logger.info("cors wrapper")
        response.view = 'generic.json'
        # response.headers['Access-Control-Allow-Origin'] ='*'
        # response.headers['Access-Control-Allow-Methods']='GET, POST,OPTIONS'
        # response.headers['Access-Control-Max-Age']= '3600'
        # response.headers['Access-Control-Allow-Headers']='Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Max-Age, X-Auth-Token, Content-Type, Accept'
        return self()
    return wrapper

def requires_token(self):
    def wrapper():
        token = request.env.http_cube_user_token or request.vars._token
        if token!=None:
            logger.info('token: %s' % token)
            row = db.cube_token(token=token)
            if row:
                # user = db.cube_user(row.user_id)
                return self()
        return dict(error='Not authorized',code=403)
    return wrapper


@cors
@request.restful()
def test():
    def GET(*args, **vars):
        return dict(content="1",aa=122)
    def POST(*args, **vars):
        return dict(content="1",aa=122)
    def OPTIONS(*args, **vars):
        return dict(content="2")
    return locals()


@cors
@request.restful()
def user():
    def GET(*args, **vars):
        logger.info("tpye %s" % 'get')
        return dict(user = db.cube_user(*args))
    def POST(*args, **vars):
        return dict(db.cube_user.validate_and_insert(**vars),content="1",aa=122)
    return locals()

@cors
@request.restful()
def findpw():
    def GET(*args, **vars):
        logger.info("tpye %s" % 'get')
        return dict(user = db(db.cube_user.username==args[0]).select(db.cube_user.id,db.cube_user.username))
    def POST(*args, **vars):
        logger.info(vars)
        if vars['code']=='1234':
            ret = db(db.cube_user.username==vars['username']).validate_and_update(password=vars['password'])
            logger.info(ret)
            return dict(ret)
        else:
            return dict(errors="code")
    return locals()

@cors
@request.restful()
def login():
    def GET(*args, **vars):
        logger.info("tpye %s" % 'get')
        return dict(user = db.cube_user(*args))
    def POST(*args, **vars):
        logger.info(vars)
        return dict(content="1",aa=122)
    return locals()
